﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Configuration;
using System.Net.NetworkInformation;

namespace OpenKVM
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var flag = true;
      
            var ip = ConfigurationManager.AppSettings["kvmIP"];
            if (string.IsNullOrEmpty(ip))
            {
                flag = false;
                MessageBox.Show("KVM IP配置不正确");
            }
            var pingFlag = TestNetConnectity(ip, 200);
            if (!pingFlag)
            {
                flag = false;
                MessageBox.Show($"KVM IP{ip} 无法连接，请检查网络");
            }
            if (flag)
                StartWinclient(ip);
            Thread.Sleep(1000);
            this.Close();
        }

        private void StartWinclient(string ip)
        {
            var exePath = AppDomain.CurrentDomain.BaseDirectory + @"WinClient\WinClient.exe";
            var port = "9000";
            var user_name = "administrator";
            var password = "Password";
            var AppPath = $"{ip}:{port}:0 -u {user_name} -p {password}";
            Thread thread = new Thread(() =>
            {
                var cmd = new Process();
                cmd.StartInfo.FileName = exePath;
                cmd.StartInfo.Arguments = AppPath;
                cmd.Start();
            });
            thread.IsBackground = true;
            thread.Start();
        }

        private bool TestNetConnectity(string strIP, int WaitSecond)
        {
            bool result = false;
            try
            {
                using (Ping pingSender = new Ping())
                {
                    PingReply reply = pingSender.Send(strIP, WaitSecond);
                    if (reply.Status == IPStatus.Success)
                        result = true;
                }
            }
            catch (Exception ex)
            {
                result = false;
                return false;
            }
            return result;
        }
    }
}
